﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace PrinterMonitorSvc.Ext
{
    /// <summary>
    /// 集合扩展类
    /// </summary>
    public static class IEnumerableExtend
    {
        #region 集合转DataTable
        /// <summary>
        /// 集合转DataTable
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="source"></param>
        /// <param name="tableName">数据表名称</param>
        /// <returns></returns>
        public static DataTable ToDataTable<T>(this IEnumerable<T> source, string tableName = null) where T : class
        {
            Type type = typeof(T);
            DataTable table = new DataTable(tableName);
            if (type == typeof(string))
            {
                return table;
            }
            List<PropertyInfo> propList = new List<PropertyInfo>();
            Array.ForEach(type.GetProperties(), p =>
            {
                propList.Add(p);
                table.Columns.Add(p.Name, p.PropertyType);
            });
            foreach (var item in source)
            {
                DataRow row = table.NewRow();
                propList.ForEach(p =>
                {
                    row[p.Name] = p.GetValue(item, null);
                });
                table.Rows.Add(row);
            }
            return table;
        }
        #endregion

        #region 根据指定对象进行去重处理
        /// <summary>
        /// 根据指定对象进行去重处理
        /// </summary>
        /// <typeparam name="TSource"></typeparam>
        /// <typeparam name="TResult"></typeparam>
        /// <param name="source"></param>
        /// <param name="filter"></param>
        /// <returns></returns>
        public static IEnumerable<TSource> DistinctBy<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, TResult> filter)
        {
            HashSet<TResult> filterSet = new HashSet<TResult>();
            foreach (var item in source)
            {
                if (filterSet.Add(filter(item)))
                {
                    yield return item;
                }
            }
        }
        #endregion

        #region 集合是否为空
        /// <summary>
        /// 集合是否为空
        /// </summary>
        /// <param name="value">集合值</param>
        public static bool IsListEmpty<T>(this IEnumerable<T> value)
        {
            return null == value || value.Count() <= 0;
        } 
        #endregion
    }
}
